package com.library.view;

import com.library.controller.AdminUserController;
import com.library.entity.Pagination;
import com.library.pojo.dto.user.UserPageQueryDTO;
import com.library.pojo.vo.UserVO;
import com.library.result.PageResult;
import com.library.result.Result;
import com.library.view.components.*;
import com.library.entity.tableCol.UserCol;
import io.yukk1o.easytermui.EasyTermUI;
import io.yukk1o.easytermui.component.Button;
import io.yukk1o.easytermui.component.InputBox;
import io.yukk1o.easytermui.component.Panel;
import io.yukk1o.easytermui.component.Text;
import io.yukk1o.easytermui.component.complex.table.Table;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import static io.yukk1o.easytermui.EasyTermUI.writer;

/**
 * 用户管理面板
 * <p>
 * 包含组件:
 * 顶部：返回按钮、新增用户按钮、搜索输入框（ID/用户名）、搜索按钮
 * 中间：用户列表（支持分页），显示ID/用户名，末尾带修改/删除按钮
 * 底部：页码显示（当前/最大）、上下页翻页按钮
 * <p>
 * 交互流程:
 * 1. 点击返回/按ESC → 返回上一界面；
 * 2. 点击新增用户按钮 → 打开新增用户弹窗；
 * 3. 点击输入框可调整光标位置，点击搜索按钮 → 筛选数据并展示；
 * 4. 点击翻页按钮 → 执行翻页并回显数据；
 * 5. 点击修改按钮 → 进入修改用户信息界面；
 * 6. 点击删除按钮：
 * - 第一次点击：按钮文本从“删除”变为“确认删除”；
 * - 第二次点击：若用户无未归还图书，删除数据并回显界面；若有未归还图书，进入失败界面并提示原因。
 */
public class UserManagePanel {

    // 创建用户控制器
    private AdminUserController adminUserController;
    private Pagination pagination;
    private Panel rootPanel;
    private boolean init = false;
    private EasyTermUI easyTermUI = new EasyTermUI();
    private UserPageQueryDTO userPageQueryDTO;
    private Table users_Table;
    Text line1, title, line2, user_Id_Text, user_Name_Text,line3,pageText;
    InputBox user_Id_Input, user_Name_Input;
    Button select_User_Button, add_User_Button,prevButton,nextButton;
    LinkedHashMap<String, Integer> colMeta;

    public UserManagePanel() {
        adminUserController = new AdminUserController();
        //分页管理器
        pagination = new Pagination();
        pagination.setPageSize(25);
//        pagination.setPageSize();
        // 创建根面板（整个终端界面）
        rootPanel = new Panel(0, 0, 120, 40);

// 标题文本
        Text line1 = new Text(0, 1, 120, 1, "========================================================================================================================");
        Text title = new Text(57, 3, 5, 1, "图书馆系统");
        Text line2 = new Text(0, 5, 120, 1, "========================================================================================================================");

        //分隔线
        Text line3 = new Text(0, 10, 120, 1, "------------------------------------------------------------------------------------------------------------------------");
        rootPanel.addComponent(line3);
        rootPanel.addComponent(line1);
        rootPanel.addComponent(title);
        rootPanel.addComponent(line2);

        /// 返回按钮
        CommonButton backButton = new CommonButton(1, 3, " <<<< ", ( )-> {
            easyTermUI.stop();
        });
        rootPanel.addComponent(backButton);

        /// id输入框
        Text idText = new Text(3, 8, 3, 1, "ID:");
        InputBox idInput = new InputBox(7, 8, 6);
        rootPanel.addComponent(idText);
        rootPanel.addComponent(idInput);

        user_Id_Text = new Text(10, 7, 5, 1, "用户ID:");

        user_Id_Input = new InputBox(20, 7, 8);
        rootPanel.addComponent(user_Id_Text);
        rootPanel.addComponent(user_Id_Input);

        //用户名查询输入框
        user_Name_Text = new Text(50, 7, 5, 1, "用户名:");

        user_Name_Input = new InputBox(60, 7, 15);
        rootPanel.addComponent(user_Name_Text);
        rootPanel.addComponent(user_Name_Input);

        //查询按钮
        select_User_Button = new Button(100, 7, "查询", (button) -> {
            String str = user_Id_Input.getValue();
            if(str == null) {
                userPageQueryDTO.setUserId(null);
            }else{
                userPageQueryDTO.setUserId(Integer.parseInt(str));
            }
            userPageQueryDTO.setUsername(user_Name_Input.getValue());
            refresh(1);
        });
        rootPanel.addComponent(select_User_Button);

        //添加用户按钮
        add_User_Button = new Button(100, 9, "添加账号", (button) -> {
            UserAddDialog userAddDialog = new UserAddDialog(40,10);
            easyTermUI.mountNoAutoStart(userAddDialog);
            refresh(1);
            easyTermUI.start();
        });
        rootPanel.addComponent(add_User_Button);

        //分隔线
        line3 = new Text(0, 10, 120, 1, "------------------------------------------------------------------------------------------------------------------------");
        rootPanel.addComponent(line3);

        //表格字段
        colMeta = new LinkedHashMap<>();
        colMeta.put("ID", 20);
        colMeta.put("用户名", 69);
        colMeta.put("      操作", 29);
        //表格数据
        users_Table = new Table(0, 11, 25, colMeta);
        rootPanel.addComponent(users_Table);

        //查询条件初始化
        userPageQueryDTO = new UserPageQueryDTO(1, pagination.getPageSize(), null, null);

        refresh(1);

        // 页码显示
        pageText = new Text(59, 39, 10, 1, getPageInfoText());
        rootPanel.addComponent(pageText);

        // 上下页翻页按钮
        prevButton = new Button(43, 39, " 上一页 ", (button) -> {
            if (pagination.prev()) {
                refresh(pagination.getCurrentPage());
            }
        });
        rootPanel.addComponent(prevButton);

        nextButton = new Button(69, 39, " 下一页 ", (button -> {
            if (pagination.next()) {
                refresh(pagination.getCurrentPage());
            }
        }));
        rootPanel.addComponent(nextButton);

        init = true;
        // 初始化界面
        easyTermUI.init(rootPanel);
    }

    private List<UserCol> getUserCols(PageResult pageResult) {
        List<UserVO> records = pageResult.getRecords();
        List<UserCol> userCols = new ArrayList<>();
        for (UserVO userVO : records) {
            int userId = userVO.getUserId();

            String userName = userVO.getUsername();

            List<Button> Buttons = getButtons(userVO);

            ButtonPanel buttonPanel = new ButtonPanel(0, 0, Buttons, 2);

            UserCol userCol = new UserCol(userId, userName, buttonPanel);
            userCols.add(userCol);
        }
        return userCols;
    }

    private List<Button> getButtons(UserVO userVO) {
        Button removeButton = new Button(0, 0, "删除", (button) -> {
            /// TODO: 确认删除逻辑
            ConfirmDialog confirmDialog = new ConfirmDialog(45, 15,"请慎重决定是否删除");
            easyTermUI.mountNoAutoStart(confirmDialog);
            confirmDialog.clear();
            writer.flush();
            easyTermUI.render();
            int resultCode = confirmDialog.getResultCode();
            if (resultCode == 1) {
                Result<String> result = adminUserController.deleteById(userVO.getUserId());
                if (result.getCode() == 1) {
                    easyTermUI.mountNoAutoStart(new TipDialog(40, 15, "删除成功"));
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    pagination.setCurrentPage(1);
                    refresh(pagination.getCurrentPage());
                } else {
                    easyTermUI.mount(new TipDialog(40, 15, result.getMsg()));
                }
            }
            easyTermUI.start();

            /// TODO: 完成弹出错误提示
        });

        Button updateButton = new Button(0, 0, "修改", (button) -> {
            UserUpdateDialog userUpdateDialog = new UserUpdateDialog(40,10,userVO);
            easyTermUI.mount(userUpdateDialog);
        });

        removeButton.setBindData(userVO);
        updateButton.setBindData(userVO);

        List<Button> Buttons = new ArrayList<>();
        Buttons.add(removeButton);
        Buttons.add(updateButton);
        return Buttons;
    }

    private void refresh(int pageNum) {
        userPageQueryDTO.setPageNum(pageNum);

        Result<PageResult> pageResultResult = adminUserController.pageQuery(userPageQueryDTO);
        PageResult pageResult = pageResultResult.getData();

        pagination.setTotal(Math.toIntExact(pageResult.getTotal()));

        List<UserCol> userCols = getUserCols(pageResult);

        pagination.setTotal((int) pageResult.getTotal());

        users_Table.setData(userCols);

        if (init) {
            users_Table.render();
            pageText.setText(getPageInfoText());
            pageText.render();
        }
    }

    private String getPageInfoText() {
        return pagination.getCurrentPage() + " / " + pagination.getMaxPage();
    }
}
